package com.ynet.middleground.approve.listener;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.ExecutionListener;
import org.activiti.engine.impl.el.FixedValue;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Service;

import com.ynet.core.exception.BusinessException;

/**
 * @author liulx
 * @description 检查流程是否有变量
 * @date 2020-04-28 15:04
 */
@DependsOn("springContextUtils")
@Service
public class CheckVariableExistListener extends BaseListener implements ExecutionListener {

    /**
     * 需要检查的变量集合, 需要在流程中配置该监听器的时候一并配置该字段
     */
    private FixedValue variableStringList;

    @Override
    public void notify(DelegateExecution delegateExecution) {
        if (variableStringList != null) {
            // 需要检查的变量列表
            String listValue = variableStringList.getExpressionText();
            if (StringUtils.isNotBlank(listValue)) {
                List<String> variableList = Arrays.stream(listValue.split(",")).collect(Collectors.toList());
                if (variableList.isEmpty()) {
                    throw new BusinessException("待检查的变量名称不能为空", "ECAP0505");
                } else {
                    variableList.forEach(var -> {
                        Object variableInstance = getObjectVariableInstance(delegateExecution, var);
                        Optional.ofNullable(variableInstance)
                            .orElseThrow(() -> new BusinessException("变量: " + var + " 不存在", "ECAP0506"));
                    });
                }
            }
        } else {
            throw new BusinessException("监听器缺少配置变量: variableStringList", "ECAP0507");
        }
    }

}
